package demo1;

import java.lang.reflect.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 涛
 * Date: 2023-10-24
 * Time: 16:31
 */

public class ReflectClassDemo {
    public static void reflectNewInstance() {
        //反射私有的构造方法
        try {
            //先拿到一个类
            Class<?> classStudent = Class.forName("demo1.Student");
            //调用构造方法
            Constructor<?> constructor = classStudent.getDeclaredConstructor(String.class, int.class);
            //私有的属性name需要你确认才能更改
            constructor.setAccessible(true);
            Student student = (Student) constructor.newInstance("xiaoming", 15);
            System.out.println(student);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
    public static void reflectPrivateField() {
        //反射私有属性
        try {
            Class<?> classStudent = Class.forName("demo1.Student");
            Field field = classStudent.getDeclaredField("name");
            field.setAccessible(true);
            Student student = (Student)classStudent.newInstance();
            field.set(student, "caocao");
            System.out.println(student);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
    public static void reflectPrivateMethod() {
        //反射私有方法
        try {
            Class<?> classStudent = Class.forName("demo1.Student");
            Method method = classStudent.getDeclaredMethod("function");
            method.setAccessible(true);

            Student student = (Student)classStudent.newInstance();

            method.invoke(student, "我是一个反射参数");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        }
    }
    public static void main(String[] args) {
        //reflectNewInstance();
        //reflectPrivateField();
        reflectPrivateMethod();
    }
}
